/**
 * 
 */
package basicTest;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
/*
 * ava.util.concurrent中实现的原子操作类包括：
AtomicBoolean、AtomicInteger、AtomicIntegerArray、AtomicLong、AtomicReference、
AtomicReferenceArray。
 * 
 */
public class AtomicOperationDemo {
		static Integer countInt=new Integer(0);
	   static AtomicInteger count=new AtomicInteger(0);
	   public static class AddThread implements Runnable{
		@Override
		public void run() {
			for(int k=0;k<1000;k++){
				count.incrementAndGet();
			}
		 } 
	   }
	   public static class AddIntThread implements Runnable{
			@Override
			public void run() {
			
					for(int k=0;k<1000;k++){
						countInt++;
					}
				
				
			 } 
		   }
	   //Atomic原子操作线程测试
	   public static void AtomicIntShow(){
		 System.out.println("AtomicIntShow() enter");
		 ExecutorService threadpool =   Executors.newFixedThreadPool(10);
		Long now= System.currentTimeMillis();
		 for(int k=0;k<100;k++){
			 threadpool.submit(new AddThread());
		 }
		 
		 try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
		 /* output
		  * AtomicIntShow() enter
		  * result of acumulated sum=100000
		  * AtomicIntShow() exit
		  */
		 
		 System.out.println("result of acumulated sum="+count);
		 threadpool.shutdown();
		 System.out.println("AtomicIntShow() exit");
		 System.out.println("AtomicIntShow()使用时间:"+(System.currentTimeMillis()-now));
		 return ;
		
	}
	   //integer测试  与Atomic做对比
	   public static void IntegerShow(){
			 System.out.println("IntegerShow() enter");
			 ExecutorService threadpool =   Executors.newFixedThreadPool(10);
			 Long now= System.currentTimeMillis();
			 for(int k=0;k<100;k++){
				 threadpool.submit(new AddIntThread());
			 }
			 
			 try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			 
			 /* output
			  * AtomicIntShow() enter
			  * result of acumulated sum=100000
			  * AtomicIntShow() exit
			  */
			 
			 System.out.println("result of acumulated sum="+countInt);
			 threadpool.shutdown();
			 System.out.println("IntegerShow() exit");
			 System.out.println("IntegerShow()使用时间:"+(System.currentTimeMillis()-now));
			 return ;
			
		}
	   public static void main(String[] args) {  
		   AtomicOperationDemo.AtomicIntShow(); 
		   AtomicOperationDemo.IntegerShow();
		}  

}

